package com.zzyl.framework.interceptor;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.zzyl.common.thread.UserTheadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@RequiredArgsConstructor
@Slf4j
public class MemberInterceptor implements HandlerInterceptor {
    private final TokenService tokenService;



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        1 验证是否是controller方法
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
//        2,验证请求头的token是否为空
        String token = request.getHeader("authorization");
        if (StrUtil.isEmpty(token)) {
            log.info("请求头为空");
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            return false;
        }
//        3,判断token是否解析为空
        Claims claims = tokenService.parseToken(token);
        if (MapUtil.isEmpty(claims)) {
            log.info("token解析为空");
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            return false;
        }
//        4,判断token获取值是为空
        Long userId = MapUtil.get(claims, "userId", Long.class);
        if (ObjectUtil.isNull(userId)) {
            log.info("token获取值是为空");
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            return false;
        }
//        5,存入ThreadLocal中
        UserTheadLocal.setUser(userId);
        log.info("用户id:{}", userId);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserTheadLocal.clean();
    }
}
